package com.qding.park.common.utils.rchl;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;


public class RchlPropertiesUtil {
	
	private static Properties pro;
	
	private static String path;
	
	
	private static void init(){
		
		pro = new Properties();
		InputStream fin;
		
		try {
			path = Thread.currentThread().getContextClassLoader().getResource("").getFile();
			File srcProperties = new File(path);
			if(srcProperties.exists()){
				for(File f:srcProperties.listFiles()){
					try {
						if(f.isFile()){
							String fileName = f.getName();
							if(fileName.indexOf(".properties")>0){
								System.out.println("init framework  properties file:"+ fileName +"");
								pro.load(new FileInputStream(f));
							}
							
						}else{
							File secondFiles[] = f.listFiles();
							for(File secFile:secondFiles){
								if(secFile.isFile()){
									String fileName = secFile.getName();
									if(fileName.indexOf(".properties")>0){
										System.out.println("init framework  properties file:"+fileName +"");
										pro.load(new FileInputStream(secFile));
									}
								}
								
							}
							
						}
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}else{
				System.out.println("ERROR:System properties file init fail!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public static String getValue(String key){
		if(null == pro){
			init();
		}
		return pro.getProperty(key) ==null ? "":pro.getProperty(key).trim();
	}
	
	public static String getValue(String key,String encoding){
		if(null == pro){
			init();
		}
		String orgEncoding = pro.getProperty("encoding");
		if(null == orgEncoding || "".equals(orgEncoding)){
			orgEncoding = "ISO8859_1";
		}
		String val = pro.getProperty(key) ==null ? "":pro.getProperty(key).trim();
		String encodeVal = "";
		try {
			encodeVal = new String(val.getBytes(orgEncoding),encoding);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return encodeVal;
	}
	
	
	public static int getIntValue(String key){
		
		String value = getValue(key);
		
		if(RchlStringUtil.isEmpty(value)){
			return 0;
		}else{
			return Integer.parseInt(value);
		}
		
	}
	
	public static  void destoryInstance(){
		pro = null;
	}
	
	public static Properties getPropertiesFile(){
		
		if(null == pro){
			init();
		}
		
		return pro;
	}
	
	public static void setProperties(InputStream fin){
		if(null == pro){
			pro = new Properties();
		}
		try {
			pro.load(fin);
		} catch (Exception e) {
			e.printStackTrace();
		}
			
	}
	
	public static void initPropertiesData(){
		init();
	}
	
	
	
}
